<template>
  <div class="huichuanshangpin">

    <div v-loading='loading' style="padding: 20px;">
      <div style="background: rgb(249, 249, 249); padding: 20px; color: rgb(51, 51, 51);">
        自定义商品详情设置
      </div>
      <div class="kflex" style="padding: 20px;">
        <div style="width: 600px; color: rgb(51, 51, 51);">
          <div style="margin-bottom: 40px;">
            <div style="margin-bottom: 20px; font-size: 14px;">运营商</div>
            <el-select v-model="all.operator" @change="changes" style="width: 400px;" placeholder="请选择运营商">
              <!-- <el-option label="中国移动" value="10086"></el-option>
              <el-option label="中国联通" value="10000"></el-option>
              <el-option label="中国电信" value="10010"></el-option> -->
              <el-option label="中国广电" value="10099"></el-option>
            </el-select>
          </div>
          <div style="margin-bottom: 40px;" class="h100">
            <el-input v-model="all.content_1" style="width: 400px;" placeholder="例子:9元/月" ></el-input>
          </div>

          <div style="margin-bottom: 40px;" class="h200">
            <el-input v-model="all.content_2" style="width: 400px;" placeholder="例子:600G" ></el-input>
          </div>

          <div style="margin-bottom: 40px;" class="h200">
            <el-input v-model="all.content_3" style="width: 400px;" placeholder="例子:全国流量" ></el-input>
          </div>

          <div style="margin-bottom: 40px;" class="h200">
            <el-input v-model="all.content_4" style="width: 400px;" placeholder="例子:80分钟通话" ></el-input>
          </div>

          <div style="margin-bottom: 40px;" class="h200">
            <el-input v-model="all.content_5" style="width: 400px;" placeholder="例子:首月免费用" ></el-input>
          </div>

          <div style="margin-bottom: 40px;">
            <div style="margin-bottom: 20px; font-size: 14px;">背景</div>
            <el-select v-model="all.background" @change="change2" style="width: 400px;" placeholder="请选择背景">
              <el-option :value="1" label="浅蓝">
                <div class="kflexbc">
                  <div><img src="https://photo.91haoka.cn/mobanbeijingtu3.png" style="width: 30px;"></div>
                  <div>浅蓝</div>
                </div>
              </el-option>
              <el-option :value="2" label="紫色">
                <div class="kflexbc">
                  <div><img src="https://photo.91haoka.cn/mobanbeijingtu4.png" style="width: 30px;"></div>
                  <div>紫色</div>
                </div>
              </el-option>
              <el-option :value="3" label="深蓝">
                <div class="kflexbc">
                  <div><img src="https://photo.91haoka.cn/mobanbeijingtu5.png" style="width: 30px;"></div>
                  <div>深蓝</div>
                </div>
              </el-option>
              <el-option :value="4" label="绿色">
                <div class="kflexbc">
                  <div><img src="https://photo.91haoka.cn/mobanbeijingtu6.png" style="width: 30px;"></div>
                  <div>绿色</div>
                </div>
              </el-option>
            </el-select>
          </div>

        </div>

        <div>

          <div id="content" style="width: 400px; margin-left: 60px; margin-top: 20px; height: 400px;  position: relative;">
            <img :src="src2" style="width: 400px;">
            <div style="position: absolute; left: 20px; top: 20px;"><img :src="src" style="width: 134px;"></div>
            <div style="position: absolute; right: 20px; top: 20px; color: #fff; font-size: 36px;">{{all.content_1}}</div>
            <div style="position: absolute; left: 20px; top: 80px; width: 360px; height: 220px;  background: #fff; border-radius: 10px;">
              <div style="width: 100%; height: 100%; position: relative;">
                <div style="position: absolute; left: 20px; bottom: 80px; font-size: 110px; color: #FF150E; font-family: fantasy; line-height: 1; width: 248px; text-align: center;">{{all.content_2}}</div>
                <div style="position: absolute; right: 20px; bottom: 80px; width: 72px; font-size: 36px; line-height: 40px;">{{all.content_3}}</div>
                <div style="position: absolute; width: 100%; text-align: center; bottom: 20px; line-height: 40px; font-size: 36px;">{{all.content_4}}</div>
              </div>
            </div>
            <div style="position: absolute; width: 100%; bottom: 18.5px; line-height: 60px; font-size: 34px; font-weight: bold; color: rgb(255, 255, 255);" class="kflexcc">
              {{all.content_5}}
            </div>
          </div>

          <div class="kflexcc" style="margin-top: 30px;  margin-left: 60px;">
            <el-button type="primary" plain :loading="loading" @click="fuzhi">复制</el-button>
            <el-button type="primary" plain :loading="loading" @click="xiazai">下载</el-button>
          </div>

        </div>




      </div>
      <div class="kflexcc" style="margin-top: 30px;">
        <el-button type="danger" :loading="loading" @click="shengchengtupian">保存</el-button>
      </div>
    </div>

  </div>
</template>

<script>
  import * as qiniu from 'qiniu-js'
  import axios from 'axios'
  import top from '@/components/top.vue'
  import left from '@/components/left.vue'
  import wenzhanglei from '@/components/zujian/wenzhanglei.vue'


  export default {
    components: {
      "left": left,
      "top": top,
      wenzhanglei
    },
    name: 'daliangset',
    data() {
      return {
        all: {
          id:'',
          operator:'10099',
          background:1,
          content_1:"9元/月",
          content_2:"600G",
          content_3:"全国流量",
          content_4:"80分钟通话",
          content_5:"首月免费用",
          thumb:''
        },
        loading:true,
        src:'https://photo.91haoka.cn/lgyidong.png',
        src2:'https://photo.91haoka.cn/mobanbeijingtu8.png'
      }
    },


    created() {
      if(this.$route.query.id){
        axios.get(`/api/plan-market/tool/main/picture/list?id=${this.$route.query.id}`)
        	.then(response => {
        		if (response.data.msg.code == 0) {

              this.all = response.data.data.data[0]

              if(this.all.operator == 10086){
                this.src = 'https://photo.91haoka.cn/lgyidong.png'
              }
              if(this.all.operator == 10000){
                this.src = 'https://photo.91haoka.cn/lgliantong.png'
              }
              if(this.all.operator == 10010){
                this.src = 'https://photo.91haoka.cn/lgdianxin.png'
              }
              if(this.all.operator == 10099){
                this.src = 'https://photo.91haoka.cn/lgguangdian.png'
              }

              if(this.all.background == 1){
                this.src2 = 'https://photo.91haoka.cn/mobanbeijingtu8.png'
              }

              if(this.all.background == 2){
                this.src2 = 'https://photo.91haoka.cn/mobanbeijingtu7.png'
              }

              if(this.all.background == 3){
                this.src2 = 'https://photo.91haoka.cn/mobanbeijingtu9.png'
              }

              if(this.all.background == 4){
                this.src2 = 'https://photo.91haoka.cn/mobanbeijingtu10.png'
              }

              this.loading = false
        		} else {
              that.$message.error(response.data.msg.info);
        		}
        	})
      }else{
        this.loading = false
      }
    },
    methods: {
      change2:function(){
        if(this.all.background == 1){
          this.src2 = 'https://photo.91haoka.cn/mobanbeijingtu8.png'
        }

        if(this.all.background == 2){
          this.src2 = 'https://photo.91haoka.cn/mobanbeijingtu7.png'
        }

        if(this.all.background == 3){
          this.src2 = 'https://photo.91haoka.cn/mobanbeijingtu9.png'
        }

        if(this.all.background == 4){
          this.src2 = 'https://photo.91haoka.cn/mobanbeijingtu10.png'
        }
      },
      changes:function(){
        if(this.all.operator == 10086){
          this.src = 'https://photo.91haoka.cn/lgyidong.png'
        }
        if(this.all.operator == 10000){
          this.src = 'https://photo.91haoka.cn/lgliantong.png'
        }
        if(this.all.operator == 10010){
          this.src = 'https://photo.91haoka.cn/lgdianxin.png'
        }
        if(this.all.operator == 10099){
          this.src = 'https://photo.91haoka.cn/lgguangdian.png'
        }
      },
      changename1: function(item) {
        console.log(item)
        this.all.name1 = item
      },
      changename2: function() {

      },
      changename3: function() {

      },
      changename4: function() {

      },
      changename5: function() {

      },

      dataURLtoFile(dataurl, filename) {
        let arr = dataurl.split(","),
          mime = arr[0].match(/:(.*?);/)[1],
          bstr = atob(arr[1]),
          n = bstr.length,
          u8arr = new Uint8Array(n);
        while (n--) {
          u8arr[n] = bstr.charCodeAt(n);
        }
        return new File([u8arr], filename, {
          type: mime
        });
      },

      getRandomChar:function(len = 11)  {
        var  x = "0123456789qwertyuioplkjhgfdsazxcvbnm" // 需要什么字符这里添加
        var  tmp = ""
        var timestamp = new Date().getTime();
        for(var  i=0;i<len;i++)  {
          tmp += x.charAt(Math.ceil(Math.random()*100000000)%x.length);
        }
        return  timestamp+tmp;
      },

      uploadok: function(file) {
        let name = this.getRandomChar()
        var that = this
        axios.get(`/api/system/qiniu/upload_token2`,{params:{bucket:'test91'}})
          .then(response => {
            if(response.data.msg.code == 0){

              const observer = {
                next(res){},
                error(err){},
                complete(res){

                  that.all.thumb = 'https://test91.91haoka.cn/'+ res.data

                  axios.post(`/api/plan-market/tool/main/picture/update`,that.all)
                  	.then(response => {
                  		if (response.data.msg.code == 0) {

                        that.$message.success('保存成功');
                        that.loading = false
                        that.$router.back(-1)

                  		} else {
                        that.$message.error(response.data.msg.info);
                  		}
                  	})

                }
              }
              const observable = qiniu.upload(file, name, response.data.data, {}, {})
              const subscription = observable.subscribe(observer) // 上传开始

            }else{
              this.$message.error(response.data.msg.info);
            }
          });


      },

      shengchengtupian: function() {
        this.loading = true
        var element2 = document.getElementById('content');
        html2canvas(element2, {
          useCORS: true, // 这个选项会自动处理跨域问题
          // scale: 1,//图片清晰度，越高越清楚，图片质量越大
          backgroundColor: null, //画出来的图片有白色的边框,不要可设置背景为透明色（null）
        }).then(canvas => {
          let base64 = canvas.toDataURL("image/jpeg", 0.8); // 压缩后的base64图片

          let file = this.dataURLtoFile(base64, Date.parse(Date()) + ".jpg");

          this.uploadok(file)



          // 将图像添加到DOM中
          // var a = document.createElement("a");
          // document.body.appendChild(a);
          // a.href = canvas.toDataURL('image/png');
          // a.download = "";
          // a.click();
        });
      },

      xiazai:function(){
        this.loading = true
        var element2 = document.getElementById('content');
        html2canvas(element2, {
          useCORS: true, // 这个选项会自动处理跨域问题
          // scale: 1,//图片清晰度，越高越清楚，图片质量越大
          backgroundColor: null, //画出来的图片有白色的边框,不要可设置背景为透明色（null）
        }).then(canvas => {
          let base64 = canvas.toDataURL("image/jpeg", 0.8); // 压缩后的base64图片
          let file = this.dataURLtoFile(base64, Date.parse(Date()) + ".jpg");

          // 将图像添加到DOM中
          var a = document.createElement("a");
          document.body.appendChild(a);
          a.href = canvas.toDataURL('image/png');
          a.download = "";
          a.click();

          this.loading = false
        });
      },

      fuzhi:function(){

        this.loading = true

        let file = ''

        var element2 = document.getElementById('content');
        html2canvas(element2, {
          useCORS: true, // 这个选项会自动处理跨域问题
          // scale: 1,//图片清晰度，越高越清楚，图片质量越大
          backgroundColor: null, //画出来的图片有白色的边框,不要可设置背景为透明色（null）
        }).then(canvas => {
          let base64 = canvas.toDataURL("image/jpeg", 0.8); // 压缩后的base64图片
          file = this.dataURLtoFile(base64, Date.parse(Date()) + ".jpg");

          let name = this.getRandomChar()
          var that = this
          axios.get(`/api/system/qiniu/upload_token2`,{params:{bucket:'test91'}})
            .then(response => {
              if(response.data.msg.code == 0){
                const observer = {
                  next(res){},
                  error(err){},
                  complete(res){
                    const imageUrl = 'https://test91.91haoka.cn/'+ res.data
                    fetch(imageUrl)
                      .then(response => response.blob())
                      .then(blob => {
                        // 创建一个临时 img 元素
                        const img = new Image();
                        img.src = URL.createObjectURL(blob);

                        img.onload = () => {
                          // 创建一个 canvas 元素
                          const canvas = document.createElement('canvas');
                          canvas.width = img.width;
                          canvas.height = img.height;

                          // 将图片绘制到 canvas 上
                          const ctx = canvas.getContext('2d');
                          ctx.drawImage(img, 0, 0);

                          // 将 canvas 内容转换为 PNG 格式的 Blob
                          canvas.toBlob(pngBlob => {
                            // 创建一个 ClipboardItem 对象，使用 image/png 类型

                            if (navigator.clipboard) {
                              const clipboardItem = new ClipboardItem({ 'image/png': pngBlob });

                              // 将图片复制到剪贴板
                              navigator.clipboard.write([clipboardItem])
                                .then(() => {
                                  that.loading = false
                                  that.$message.success('图片已成功复制到剪贴板');
                                })
                                .catch(err => {
                                  that.loading = false
                                  that.$message.success('无法复制图片到剪贴板:', err);
                                });
                            } else {
                              that.loading = false
                              that.$message.success('无法复制图片到剪贴板:', err);
                            }
                          }, 'image/png'); // 指定输出为 PNG 格式
                        };
                      })
                      .catch(err => {
                        that.loading = false
                        console.error('无法获取图片:', err);
                      });

                  }
                }
                const observable = qiniu.upload(file, name, response.data.data, {}, {})
                const subscription = observable.subscribe(observer) // 上传开始

              }else{
                this.$message.error(response.data.msg.info);
              }
            });

        });
      },
      add: function() {
        this.all.gaiyao.push({
          name: "",
          value: ""
        })
      },
      add2: function() {
        this.all.xiangqing.push({
          name: "",
          value: ""
        })
      },
      add3: function() {
        this.all.qita.push({
          name: "",
          value: ""
        })
      },

    }

  }
</script>

<style lang="scss" scoped>
  @import "@/assets/zuixin.scss";

  /deep/ p {
    margin-block-start: 0px;
    margin-block-end: 0px;
  }

  /deep/ .h100 {
    .w-e-text-container {
      height: 100px !important;
    }
  }

  /deep/ .h200 {
    .w-e-text-container {
      height: 200px !important;
    }
  }
  #content {
    div{ box-sizing: border-box;}
  }
</style>
